package com.pyl.admin.system.controller;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pyl.admin.core.enums.ResultEnum;
import com.pyl.admin.core.enums.StatusEnum;
import com.pyl.admin.core.exception.ResultException;
import com.pyl.admin.system.entity.SysDept;
import com.pyl.admin.system.service.SysDeptService;
import com.pyl.admin.system.validator.DeptForm;
import com.pyl.core.utils.ResultVoUtil;
import com.pyl.core.vo.ResultVo;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 灵魂贰婶
 * @since 2019-06-28
 */
@Controller
@RequestMapping("/system/dept")
public class SysDeptController {

	@Autowired
	private SysDeptService sysDeptService;

	/**
	 * 跳转到列表页面
	 */
	@GetMapping("/index")
	@RequiresPermissions("/system/dept/index")
	public String index(Model model, @RequestParam(value = "status", defaultValue = "1") Integer status,
			@RequestParam(value = "title", required = false) String title) {
		String search = "";
		if (ObjectUtil.isNotNull(status)) {
			search += "status=" + status;
		}
		if (StrUtil.isNotBlank(title)) {
			search += "&title=" + title;
		}
		model.addAttribute("search", search);
		return "/system/dept/index";
	}

	/**
	 * 部门数据列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("/system/dept/index")
	@ResponseBody
	public ResultVo<?> list(@RequestParam(value = "status", defaultValue = "1") Integer status,
			@RequestParam(value = "title", required = false) String title) {
		// 获取用户列表
		List<SysDept> list = sysDeptService.selectDeptList(status, title);
		return ResultVoUtil.success(list);
	}

	/**
	 * 获取排序菜单列表
	 */
	@GetMapping("/sortList/{pid}/{notId}")
	@RequiresPermissions({ "/system/dept/add", "/system/dept/edit" })
	@ResponseBody
	public Map<Integer, String> sortList(@PathVariable(value = "pid", required = false) Long pid,
			@PathVariable(value = "notId", required = false) Long notId) {
		// 本级排序菜单列表
		notId = notId != null ? notId : (long) 0;
		List<SysDept> levelDept = sysDeptService.selectList(new EntityWrapper<SysDept>().eq("pid", pid).ne("id", notId)
				.eq("status", Integer.valueOf(StatusEnum.OK.getCode())));
		Map<Integer, String> sortMap = new TreeMap<>();
		for (int i = 1; i <= levelDept.size(); i++) {
			sortMap.put(i, levelDept.get(i - 1).getTitle());
		}
		return sortMap;
	}

	/**
	 * 跳转到添加页面
	 */
	@GetMapping({ "/add", "/add/{pid}" })
	@RequiresPermissions("/system/dept/add")
	public String toAdd(@PathVariable(value = "pid", required = false) Long pid, Model model) {
		// 父级部门
		if (pid != null) {
			SysDept pDept = sysDeptService.selectById(pid);
			model.addAttribute("pDept", pDept);
		}
		return "/system/dept/add";
	}

	/**
	 * 跳转到编辑页面
	 */
	@GetMapping("/edit/{id}")
	@RequiresPermissions("/system/dept/edit")
	public String toEdit(@PathVariable("id") Long id, Model model) {
		SysDept dept = sysDeptService.selectById(id);
		SysDept pDept = sysDeptService.selectById(dept.getPid());
		if (pDept == null) {
			SysDept newDept = new SysDept();
			newDept.setId((long) 0);
			newDept.setTitle("顶级");
			pDept = newDept;
		}
		model.addAttribute("dept", dept);
		model.addAttribute("pDept", pDept);
		return "/system/dept/add";
	}

	/**
	 * 保存添加/修改的数据
	 *
	 * @param deptForm 表单验证对象
	 */
	@PostMapping("/save")
	@RequiresPermissions({ "/system/dept/add", "/system/dept/edit" })
	@ResponseBody
	public ResultVo<?> save(@Validated DeptForm deptForm) {
		sysDeptService.saveOrUpdate(deptForm);
		return ResultVoUtil.SAVE_SUCCESS;
	}

	/**
	 * 跳转到详细页面
	 */
	@GetMapping("/detail/{id}")
	@RequiresPermissions("/system/dept/detail")
	public String toDetail(@PathVariable("id") Long id, Model model) {
		SysDept sysDept = sysDeptService.selectById(id);
		model.addAttribute("dept", sysDept);
		return "/system/system/dept/detail";
	}

	/**
	 * 设置一条或者多条数据的状态
	 */
	@RequestMapping("/status/{param}")
	@RequiresPermissions("/system/dept/status")
	@ResponseBody
	public ResultVo<?> status(@PathVariable("param") String param,
			@RequestParam(value = "ids", required = false) List<Long> idList) {
		if (idList.size() > 2) {
			return ResultVoUtil.error("失败，只允许选择一个");
		}
		try {
			// 获取状态StatusEnum对象
			StatusEnum statusEnum = StatusEnum.valueOf(param.toUpperCase());
			// 更新状态
			boolean result =  sysDeptService.updateStatus(statusEnum,idList);
			return result ? ResultVoUtil.success(statusEnum.getMessage() + "成功") : ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
		} catch (IllegalArgumentException e) {
			throw new ResultException(ResultEnum.STATUS_ERROR);
		}
	}
}
